
package net.swa.dewei.service.impl;

import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.Date;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import org.apache.commons.lang.StringUtils;
import org.apache.log4j.Logger;
import org.hibernate.Query;
import org.hibernate.Session;
import org.hibernate.type.StandardBasicTypes;
import org.springframework.stereotype.Service;
import net.sf.json.JSONArray;
import net.sf.json.JSONObject;
import net.swa.dewei.beans.entity.WeixinInfo;
import net.swa.dewei.beans.entity.WxDateReport;
import net.swa.dewei.beans.vo.DataSerie;
import net.swa.dewei.beans.vo.ReportWxDate;
import net.swa.dewei.beans.vo.WeixinStatis;
import net.swa.dewei.service.WeixinInfoService;
import net.swa.dewei.thread.SynWxInfoThread;
import net.swa.system.dao.HibernateDaoSupport;
import net.swa.util.BuzConst;
import net.swa.util.DateUtils;
import net.swa.util.FileUtil;
import net.swa.util.JsonResult;
import net.swa.util.MySecureProtocolSocketFactory;
import net.swa.util.StringUtil;

@Service("weixinInfoService")
public class WeixinInfoServiceImpl extends HibernateDaoSupport implements WeixinInfoService
{
    private final Logger log = Logger.getLogger(WeixinInfoServiceImpl.class);

    public void saveOrUpdateByManu(final WeixinInfo wx)
    {
        WeixinInfo m = (WeixinInfo) getCurrentSession().get(WeixinInfo.class, wx.getId());
        if (null == m)
        {
            wx.setStatus(BuzConst.WX_GUANZHU);
            wx.setUpdateTime(DateUtils.getCurrDate(null));
            wx.setGuazhuTime(DateUtils.getCurrDate(null));
            wx.setQuxiaoTime(null);
            getCurrentSession().save(wx);
        }
        else
        {
            m.setUpdateTime(DateUtils.getCurrDate(null));
            //手动同步更新微信信息，仅修改更新时间，不修改关注/取消关注时间
            //m.setGuazhuTime(wx.getGuazhuTime());
            //m.setQuxiaoTime(wx.getQuxiaoTime());
            m.setCity(wx.getCity());
            m.setProvince(wx.getProvince());
            m.setHeadimgurl(wx.getHeadimgurl());
            m.setLanguage(wx.getLanguage());
            m.setNickname(wx.getNickname());
            m.setProvince(wx.getProvince());
            m.setSex(wx.getSex());
            m.setSheadimgurl(wx.getSheadimgurl());
            m.setSubscribe(wx.getSubscribe());
            m.setSubscribe_time(wx.getSubscribe_time());
            m.setCountry(wx.getCountry());
            m.setStatus(BuzConst.WX_GUANZHU);
            getCurrentSession().update(m);
        }
    }

    @Override
    public WeixinInfo queryById(final String id)
    {

        WeixinInfo m = (WeixinInfo) getCurrentSession().get(WeixinInfo.class, id);
        return m;
    }

    @Override
    public void saveModel(final WeixinInfo model)
    {

        getCurrentSession().saveOrUpdate(model);

    }

    public void dowork()
    {
        if (SynWxInfoThread.hasThreadRunning())
        {
            if (log.isDebugEnabled())
            {
                log.debug("定时执行同步任务无法开启，已经有用户正在执行同步");
            }
        }
        else
        {
            // 将完成同步的记录数置0
            SynWxInfoThread.setC(0);
            String token;
            try
            {
                token = getToken();
                if (tongbu(token, ""))
                {
                    while (true)
                    {// 等待所有子线程执行完
                        if (!SynWxInfoThread.hasThreadRunning())
                        {
                            break;
                        }
                        Thread.sleep(500);
                    }
                    if (log.isDebugEnabled())
                    {
                        log.debug("定时执行同步任务成功完成！");
                    }
                }
                else
                {
                    if (log.isDebugEnabled())
                    {
                        log.debug("定时执行同步任务出现异常");
                    }
                }
            }
            catch (Exception e)
            {
                if (log.isDebugEnabled())
                {
                    log.debug("定时执行同步任务出现异常");
                }
                e.printStackTrace();
            }

        }
    }

    private String getToken() throws Exception
    {
        String token = null;
        String resp = MySecureProtocolSocketFactory.get(BuzConst.HTTP_WX_TOKEN + "?grant_type=client_credential&appid=" + BuzConst.APPID + "&secret=" + BuzConst.SECRET);
        JSONObject jsonObj = JSONObject.fromObject(resp);
        token = (String) jsonObj.get("access_token");
        return token;
    }

    private boolean tongbu(final String token , String next_openid) throws Exception
    {
        if (log.isDebugEnabled())
        {
            log.debug("定时执行同步任务开始更新，   token 为：" + token);
        }
        String http = BuzConst.HTTP_WX_USER_LIST + "?access_token=" + token + "&next_openid=" + next_openid;
        String resp = MySecureProtocolSocketFactory.get(http);
        JSONObject jsonObj = JSONObject.fromObject(resp.toString());
        Object errcode = (Object) jsonObj.get("errcode");
        if (null != errcode)
        {
            // 如果错误码不为空
            if (log.isDebugEnabled())
            {
                log.debug("定时执行同步任务失败，错误码为：" + errcode);
            }
        }
        else
        {
            int total = (Integer) jsonObj.get("total");
            int count = (Integer) jsonObj.get("count");
            String nexOpenid = (String) jsonObj.get("next_openid");
            JSONObject data = jsonObj.getJSONObject("data");
            JSONArray array = data.getJSONArray("openid");
            if (null != array)
            {
                Iterator<?> it = array.iterator();
                ExecutorService pool = Executors.newFixedThreadPool(BuzConst.NUM_THREAD);
                while (it.hasNext())
                {
                    final String openId = (String) it.next();
                    final SynWxInfoThread qu = new SynWxInfoThread(token, openId, getOpenSession(), total);
                    // 创建实现了Runnable接口对象，Thread对象当然也实现了Runnable接口
                    pool.execute(qu);
                }
            }
            if (total > count && count > 0 && (!StringUtils.isBlank(nexOpenid)))
            {
                tongbu(token, nexOpenid);
            }
        }
        return true;
    }

    @Override
    public void delete(final String[] ids)
    {
        Query query = getCurrentSession().createQuery("delete from WeixinInfo  where id=:id");
        for (int i = 0; i < ids.length; i++)
        {
            if (null != ids[i])
            {
                query.setString("id", ids[i]);
                query.executeUpdate();
            }
        }
    }

    @SuppressWarnings("unchecked")
    @Override
    public JsonResult<WeixinInfo> queryWeixinPage(final String nickName , final String wxid , final int currentPage , final int pageSize)
    {
        JsonResult<WeixinInfo> json = new JsonResult<WeixinInfo>();
        List<WeixinInfo> list = new ArrayList<WeixinInfo>();
        StringBuilder hql = new StringBuilder().append(" from WeixinInfo  where 1=1 ");
        if (!StringUtils.isBlank(nickName))
        {
            hql.append(" and nickName like :nickName ");
        }
        if (!StringUtils.isBlank(wxid))
        {
            //            hql.append("  or id=:wxid ");
            //			hql.append(" and ( mendian =:mendian or id=:wxid)");
        }
        else
        {
            //			hql.append(" and  mendian =:mendian ");
        }
        Query q = getCurrentSession().createQuery(hql.toString());
        if (!StringUtils.isBlank(nickName))
        {
            q.setString("nickName", "%" + nickName + "%");
        }
        if (!StringUtils.isBlank(wxid))
        {
            //            q.setString("wxid", wxid);
            //			q.setBoolean("mendian", false);
        }
        else
        {
            //			q.setBoolean("mendian", false);
        }
        if (pageSize > 0)
        {
            int from = (currentPage - 1) * pageSize;
            q.setFirstResult(from);
            q.setMaxResults(pageSize);
        }
        list = q.list();
        q = getCurrentSession().createQuery("select count(*) " + hql);
        if (!StringUtils.isBlank(nickName))
        {
            q.setString("nickName", "%" + nickName + "%");
        }
        if (!StringUtils.isBlank(wxid))
        {
            //            q.setString("wxid", wxid);
            //			q.setBoolean("mendian", false);
        }
        else
        {
            //			q.setBoolean("mendian", false);
        }
        if (pageSize > 0)
        {
            int totalCount = ((Number) (q.iterate().next())).intValue();
            int totalPage = totalCount % pageSize == 0 ? totalCount / pageSize : totalCount / pageSize + 1;
            json.setTotalSize(totalCount);
            json.setTotalPage(totalPage);
            json.setPageSize(pageSize);
            json.setCurrentPage(currentPage);
        }
        json.setResult(list);
        return json;
    }

    @Override
    public void batchUpdate(final List<WeixinInfo> list)
    {
        if (null != list && list.size() > 0)
        {
            Iterator<WeixinInfo> it = list.iterator();
            while (it.hasNext())
            {
                WeixinInfo wx = it.next();
                WeixinInfo m = (WeixinInfo) getCurrentSession().get(WeixinInfo.class, wx.getId());
                if (null == m)
                {
                    getCurrentSession().save(wx);
                }
                else
                {
                    m.setCity(wx.getCity());
                    m.setProvince(wx.getProvince());
                    m.setHeadimgurl(wx.getHeadimgurl());
                    m.setLanguage(wx.getLanguage());
                    m.setNickname(wx.getNickname());
                    m.setProvince(wx.getProvince());
                    m.setSex(wx.getSex());
                    m.setSheadimgurl(wx.getSheadimgurl());
                    m.setSubscribe(wx.getSubscribe());
                    m.setSubscribe_time(wx.getSubscribe_time());
                    m.setCountry(wx.getCountry());
                    log.debug("更新微信信息：" + m);
                    getCurrentSession().update(m);
                }
            }
        }
    }

    @Override
    public void saveOrUpdateModel(String openId , String token , boolean b)
    {
        if (b)
        {
            if (!StringUtils.isBlank(token))
            {
                WeixinInfo wx = null;
                String nickname = null;
                String http = BuzConst.HTTP_WX_USER_INFO + "?access_token=" + token + "&openid=" + openId;
                String resp;
                try
                {
                    resp = MySecureProtocolSocketFactory.get(http);
                    JSONObject jsonObj = JSONObject.fromObject(resp.toString());
                    if (null != jsonObj)
                    {
                        wx = new WeixinInfo();
                        wx.setId(openId);
                        if (null != jsonObj.get("nickname"))
                        {
                            nickname = jsonObj.get("nickname").toString();
                            nickname = StringUtil.filterStr(nickname);
                            wx.setNickname(nickname);
                        }
                        if (null != jsonObj.get("province"))
                        {
                            String province = jsonObj.get("province").toString();

                            wx.setProvince(province);
                        }
                        if (null != jsonObj.get("city"))
                        {
                            String city = jsonObj.get("city").toString();
                            wx.setCity(city);
                        }

                        if (null != jsonObj.get("headimgurl"))
                        {
                            String headimgurl = jsonObj.get("headimgurl").toString();
                            wx.setHeadimgurl(headimgurl);
                            if (headimgurl.length() > 0)
                            {
                                wx.setSheadimgurl("data:image/png;base64," + FileUtil.imageToBase64(headimgurl.substring(0, headimgurl.length() - 1) + "64"));
                            }
                        }
                        if (null != jsonObj.get("subscribe"))
                        {
                            String subscribe = jsonObj.get("subscribe").toString();
                            wx.setSubscribe(subscribe);
                        }
                        if (null != jsonObj.get("sex"))
                        {
                            String sex = jsonObj.get("sex").toString();
                            wx.setSex(sex);
                        }

                        if (null != jsonObj.get("language"))
                        {
                            String language = jsonObj.get("language").toString();
                            wx.setLanguage(language);
                        }

                        if (null != jsonObj.get("country"))
                        {
                            String country = jsonObj.get("country").toString();
                            wx.setCountry(country);
                        }
                        if (null != jsonObj.get("subscribe_time"))
                        {
                            String subscribe_time = jsonObj.get("subscribe_time").toString();
                            wx.setSubscribe_time(subscribe_time);
                        }
                        //关注
                        wx.setStatus(BuzConst.WX_GUANZHU);
                        WeixinInfo m = (WeixinInfo) getCurrentSession().get(WeixinInfo.class, openId);
                        if (null == m)
                        {
                            log.debug("增量同步-----------新增关注wxid  is ：" + openId);
                            wx.setGuazhuTime(DateUtils.getCurrDate(null));
                            wx.setUpdateTime(DateUtils.getCurrDate(null));
                            getCurrentSession().save(wx);
                        }
                        else
                        {
                            m.setCity(wx.getCity());
                            m.setProvince(wx.getProvince());
                            m.setHeadimgurl(wx.getHeadimgurl());
                            m.setLanguage(wx.getLanguage());
                            m.setNickname(wx.getNickname());
                            m.setProvince(wx.getProvince());
                            m.setSex(wx.getSex());
                            m.setSheadimgurl(wx.getSheadimgurl());
                            m.setSubscribe(wx.getSubscribe());
                            m.setSubscribe_time(wx.getSubscribe_time());
                            m.setCountry(wx.getCountry());
                            //关注
                            m.setStatus(BuzConst.WX_GUANZHU);
                            log.debug("增量同步-----------再次关注wxid  is ：" + openId);

                            m.setQuxiaoTime(wx.getQuxiaoTime());

                            m.setGuazhuTime(DateUtils.getCurrDate(null));

                            m.setUpdateTime(DateUtils.getCurrDate(null));

                            getCurrentSession().update(m);
                        }
                    }
                }
                catch (Exception e)
                {
                    log.debug("增量同步-----------出现异常");
                    e.printStackTrace();
                }
            }
            else
            {
                log.debug("增量同步-----------token出现异常");
            }
        }
        else
        {
            log.debug("增量同步-----------取消关注wxid  is ：" + openId);
            //取消关注
            Query q = getCurrentSession().createQuery("update  WeixinInfo set status=:status,updateTime=:updateTime,quxiaoTime=:quxiaoTime where id=:wxid");
            q.setInteger("status", BuzConst.WX_QUXIAO);
            q.setString("updateTime", DateUtils.getCurrDate(null));
            q.setString("quxiaoTime", DateUtils.getCurrDate(null));
            q.setString("wxid", openId);
            q.executeUpdate();
            //将门店中微信清楚，上步也应该将门店信息设置为非门店（暂时不这样做）
            //            q = getCurrentSession().createQuery("update MenDian set nickname=:nickname,wxid=:wxid2 where wxid=:wxid");
            //            q.setString("nickname", null);
            //            q.setString("wxid2", null);
            //            q.setString("wxid", openId);
            //            q.executeUpdate();
        }
    }

    @Override
    public WeixinStatis queryStatis()

    {
        WeixinStatis m = new WeixinStatis();
        Session session = getCurrentSession();
        Query q = session.createQuery("select count(*) from WeixinInfo ");

        int totalCount = ((Number) (q.iterate().next())).intValue();
        m.setTotalNum(totalCount);

        q = session.createQuery("select count(*) from WeixinInfo where status=:status");
        q.setInteger("status", BuzConst.WX_GUANZHU);
        int guanzhuNum = ((Number) (q.iterate().next())).intValue();
        m.setGuanzhuNum(guanzhuNum);
        q.setInteger("status", BuzConst.WX_QUXIAO);
        int quxiaoNum = ((Number) (q.iterate().next())).intValue();
        m.setQuxiaoNum(quxiaoNum);

        log.debug("guanzhuNum： " + guanzhuNum + "quxiaoNum：" + quxiaoNum + "=" + (guanzhuNum + quxiaoNum) + "==" + totalCount);

        q = session.createQuery("select count(*) from WeixinInfo where mendian=:mendian");
        q.setBoolean("mendian", true);
        int mendNum = ((Number) (q.iterate().next())).intValue();
        m.setMendNum(mendNum);

        q.setBoolean("mendian", false);
        int feiMendNum = ((Number) (q.iterate().next())).intValue();
        m.setFeiMendNum(feiMendNum);

        log.debug("门店： " + mendNum + "普通：" + feiMendNum + "=" + (feiMendNum + mendNum) + "==" + totalCount);

        return m;
    }

    //日报生成
    @Override
    public void saveDateReport()
    {
        Session session = getCurrentSession();
        String date = DateUtils.getCurrDate("yyyy-MM-dd");
        Query q = null;
        String hql = " from WxDateReport where date=:date";
        Calendar c = Calendar.getInstance();//可以对每个时间域单独修改
        int hour = c.get(Calendar.HOUR_OF_DAY);
        String yesterdate = DateUtils.getYesterDayDate("yyyy-MM-dd");//今天生成昨日日报
        String twoDayAgo = DateUtils.getDateCoutAgo("yyyy-MM-dd", -2);
        List<WxDateReport> l2 = null;
        if (hour < 8)
        {//若是晨8点前 生成昨日日报
            date = yesterdate;
            q = session.createQuery(hql);
            q.setString("date", twoDayAgo);
            l2 = q.list();//2天前日报  
        }
        q = session.createQuery(hql);
        q.setString("date", date);
        List<WxDateReport> l = q.list();

        if (null == l || 0 == l.size())
        {//若不存在说明日报还没有生成过,此时
            WxDateReport r = new WxDateReport();
            r.setDate(date);

            //统计即时当天新增关注的人数
            String sql = "select count(*) as plus FROM t_weixininfo where `status`=1 and guazhuTime like '" + date + "%' ";
            q = session.createSQLQuery(sql).addScalar("plus", StandardBasicTypes.INTEGER);
            Integer plus = (Integer) q.uniqueResult();
            if (null == plus)
            {
                plus = 0;
            }
            r.setPlus(plus);
            //统计即时当天取消关注的人数
            sql = "select count(*) as minus FROM t_weixininfo where `status`=2  and quxiaoTime like '" + date + "%' ";
            q = session.createSQLQuery(sql).addScalar("minus", StandardBasicTypes.INTEGER);
            Integer minus = (Integer) q.uniqueResult();
            if (null == minus)
            {
                minus = 0;
            }
            r.setMinus(minus);
            r.setRealPlus(r.getPlus() - r.getMinus());
            //统计即时关注的总人数
            sql = "SELECT count(*) as counNum  FROM t_weixininfo where `status`=1 ";
            q = session.createSQLQuery(sql).addScalar("counNum", StandardBasicTypes.INTEGER);
            Integer totalCount = (Integer) q.uniqueResult();
            r.setTotal(totalCount);
            if (null == totalCount)
            {
                r.setTotal(0);
            }

            session.save(r);
            log.debug("SUCCESS:" + date + " 当天的日报已经生成完毕");
        }
        else
        {
            WxDateReport r = l.get(0);
            //统计即时关注的总人数
            String sql = "SELECT count(*) as counNum  FROM t_weixininfo where `status`=1 ";
            q = session.createSQLQuery(sql).addScalar("counNum", StandardBasicTypes.INTEGER);
            Integer totalCount = (Integer) q.uniqueResult();
            r.setTotal(totalCount);
            if (null == totalCount)
            {
                r.setTotal(0);
            }

            //统计即时当天新增关注的人数
            sql = "select count(*) as plus FROM t_weixininfo where `status`=1 and guazhuTime like '" + date + "%' ";
            q = session.createSQLQuery(sql).addScalar("plus", StandardBasicTypes.INTEGER);
            Integer plus = (Integer) q.uniqueResult();
            if (null == plus)
            {
                plus = 0;
            }
            r.setPlus(plus);

            if (null != l2 && 1 == l2.size())
            {
                WxDateReport r2 = l2.get(0);
                r.setRealPlus(r.getTotal() - r2.getTotal());
                r.setMinus(r.getPlus() - r.getRealPlus());
            }
            else
            {
                //统计即时当天取消关注的人数
                sql = "select count(*) as minus FROM t_weixininfo where `status`=2  and quxiaoTime like '" + date + "%' ";
                q = session.createSQLQuery(sql).addScalar("minus", StandardBasicTypes.INTEGER);
                Integer minus = (Integer) q.uniqueResult();
                if (null == minus)
                {
                    minus = 0;
                }
                r.setMinus(minus);
                r.setRealPlus(r.getPlus() - r.getMinus());
            }

            session.update(r);

            log.debug("" + date + " 当天的日报已经重新生成！");
        }
    }

    @SuppressWarnings("unchecked")
    @Override
    public ReportWxDate queryDateReport(String keyType , String sdate , String edate)
    {
        ReportWxDate result = new ReportWxDate();
        result.setTitle("增长趋势图");
        result.setSubtitle("");
        if ("4".equals(keyType))
        {
            result.setTitle("累计趋势图");
            result.setSubtitle("");
        }

        Map<String, WxDateReport> map = new HashMap<String, WxDateReport>();
        String hql = " from WxDateReport where date>=:sdate and date<=:edate order by date";
        Session session = getCurrentSession();
        Query q = session.createQuery(hql);
        q.setString("sdate", sdate);
        q.setString("edate", edate);
        List<WxDateReport> l = q.list();
        if (l.size() > 0)
        {
            for (int i = 0; i < l.size(); i++)
            {
                map.put(l.get(i).getDate(), l.get(i));
            }
            List<String> categories = new ArrayList<String>();
            List<DataSerie> dataSerie = new ArrayList<DataSerie>();
            SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
            try
            {
                long end = sdf.parse(edate).getTime();
                long begin = sdf.parse(sdate).getTime();
                Map<String, String> m = new HashMap<String, String>();
                m.put("symbol", "diamond");
                DataSerie s1 = new DataSerie("新增", m);//增长
                DataSerie s2 = new DataSerie("取消", m);//取消
                DataSerie s3 = new DataSerie("净增", m);//净增
                DataSerie s4 = new DataSerie("累积", m);//总体
                List<Integer> data1 = new ArrayList<Integer>();
                List<Integer> data2 = new ArrayList<Integer>();
                List<Integer> data3 = new ArrayList<Integer>();
                List<Integer> data4 = new ArrayList<Integer>();

                int minTickInterval = 1;
                long days = (end - begin) / (3600 * 24 * 1000);
                if (days > 10 && days < 20)
                {
                    minTickInterval = 2;
                }
                else if (days >= 20)
                {
                    minTickInterval = 4;
                }
                result.setMinTickInterval(minTickInterval);
                while (begin <= end)
                {
                    Date day = new Date();
                    day.setTime(begin);
                    String date = sdf.format(day);
                    categories.add(date);
                    WxDateReport o = map.get(date);
                    if (null == o)
                    {
                        //如果没有数据则设置为0
                        data1.add(0);
                        data2.add(0);
                        data3.add(0);
                        data4.add(null);
                    }
                    else
                    {
                        data1.add(o.getPlus());
                        data2.add(o.getMinus());
                        data3.add(o.getRealPlus());
                        data4.add(o.getTotal());
                    }
                    begin += 3600 * 24 * 1000;
                }
                s1.setData(data1);
                s2.setData(data2);
                s3.setData(data3);
                s4.setData(data4);
                if ("4".equals(keyType))
                {
                    dataSerie.add(s4);
                }
                else
                {
                    dataSerie.add(s1);
                    dataSerie.add(s2);
                    dataSerie.add(s3);
                }
                result.setCategories(categories);
                result.setSeries(dataSerie);
            }
            catch (Exception e)
            {
                log.debug("Exception ," + e);
                e.printStackTrace();
            }
        }
        return result;
    }

    @SuppressWarnings("unchecked")
    @Override
    public JsonResult<WxDateReport> queryWxReportPage(String keyType , String sdate , String edate , int currentPage , int pageSize , String orderBy , String orderType)
    {
        JsonResult<WxDateReport> json = new JsonResult<WxDateReport>();
        StringBuilder hql = new StringBuilder();
        hql.append(" from WxDateReport where 1=1 ");
        if (!StringUtils.isBlank(sdate))
        {
            hql.append(" and date>=:sdate ");
        }
        if (!StringUtils.isBlank(edate))
        {
            hql.append(" and date<=:edate ");
        }
        if (!StringUtils.isEmpty(orderBy))
        {
            hql.append(" order by " + orderBy + " " + orderType);
        }

        Session session = getCurrentSession();
        Query q = session.createQuery(hql.toString());
        if (!StringUtils.isBlank(sdate))
        {
            q.setString("sdate", sdate);
        }
        if (!StringUtils.isBlank(edate))
        {
            q.setString("edate", edate);
        }
        if (pageSize > 0)
        {
            int from = (currentPage - 1) * pageSize;
            q.setFirstResult(from);
            q.setMaxResults(pageSize);
            List<WxDateReport> l = q.list();
            json.setResult(l);
            q = session.createQuery("select count(*) " + hql);
            if (!StringUtils.isBlank(sdate))
            {
                q.setString("sdate", sdate);
            }
            if (!StringUtils.isBlank(edate))
            {
                q.setString("edate", edate);
            }
            int totalCount = ((Number) (q.iterate().next())).intValue();
            int totalPage = totalCount % pageSize == 0 ? totalCount / pageSize : totalCount / pageSize + 1;
            json.setTotalSize(totalCount);
            json.setTotalPage(totalPage);
            json.setPageSize(pageSize);
            json.setCurrentPage(currentPage);
        }
        return json;
    }
}